import { saveAs } from 'file-saver';
import { marked } from 'marked';

// 类型声明以支持桌面环境检测
declare global {
  interface Window {
    electronAPI?: any;
    __TAURI__?: any;
  }
}

export const fileUtils = {
  // 读取文件
  readFile: (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => resolve(e.target?.result as string);
      reader.onerror = (e) => reject(e);
      reader.readAsText(file);
    });
  },

  // 保存文件
  saveFile: (content: string, filename: string) => {
    const blob = new Blob([content], { type: 'text/markdown;charset=utf-8' });
    saveAs(blob, filename);
  },

  // 导出为HTML
  exportToHTML: (markdown: string, customCSS?: string) => {
    const html = marked(markdown);
    const fullHTML = `
<!DOCTYPE html>
<html lang=\"zh-CN\">
<head>
    <meta charset=\"UTF-8\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title>Markdown Export</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
        }
        h1, h2, h3, h4, h5, h6 { margin-top: 24px; margin-bottom: 16px; }
        p { margin-bottom: 16px; }
        code {
            background-color: #f6f8fa;
            padding: 2px 4px;
            border-radius: 3px;
            font-size: 85%;
        }
        pre {
            background-color: #f6f8fa;
            padding: 16px;
            border-radius: 6px;
            overflow: auto;
        }
        blockquote {
            border-left: 4px solid #dfe2e5;
            padding-left: 16px;
            margin-left: 0;
            color: #6a737d;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 16px;
        }
        th, td {
            border: 1px solid #dfe2e5;
            padding: 8px 12px;
            text-align: left;
        }
        th {
            background-color: #f6f8fa;
            font-weight: bold;
        }
        ${customCSS || ''}
    </style>
</head>
<body>
    ${html}
</body>
</html>`;
    return fullHTML;
  },

  // 导出为PDF（使用Canvas渲染，支持中文）
  exportToPDF: async (content: string, filename: string) => {
    console.log('开始PDF导出:', filename);

    try {
      // 检查是否为桌面环境
      const isDesktop = window.electronAPI || window.__TAURI__;

      if (isDesktop) {
        console.log('检测到桌面环境，使用桌面端导出方案');
      }

      // 动态导入PDF相关依赖
      console.log('开始导入PDF依赖...');

      const importPromise = Promise.all([
        import('html2canvas'),
        import('jspdf')
      ]);

      // 设置10秒超时
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('导入PDF依赖超时')), 10000);
      });

      const [{ default: html2canvas }, { default: jsPDF }] = await Promise.race([
        importPromise,
        timeoutPromise
      ]) as any;

      console.log('PDF依赖导入成功');

      // 将Markdown转换为HTML并创建临时DOM元素进行渲染
      console.log('开始转换Markdown为HTML...');
      const htmlContent = marked(content);

      // 创建临时容器用于渲染
      const tempContainer = document.createElement('div');
      tempContainer.style.position = 'absolute';
      tempContainer.style.left = '-9999px';
      tempContainer.style.top = '-9999px';
      tempContainer.style.width = '800px';
      tempContainer.style.padding = '20px';
      tempContainer.style.backgroundColor = '#ffffff';
      tempContainer.style.fontFamily = '-apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "SimSun", sans-serif';
      tempContainer.style.fontSize = '14px';
      tempContainer.style.lineHeight = '1.6';
      tempContainer.style.color = '#333333';

      // 添加样式
      tempContainer.innerHTML = `
        <style>
          .temp-pdf-content {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "SimSun", sans-serif;
            font-size: 14px;
            line-height: 1.6;
            color: #333333;
            max-width: none;
          }
          .temp-pdf-content h1, .temp-pdf-content h2, .temp-pdf-content h3,
          .temp-pdf-content h4, .temp-pdf-content h5, .temp-pdf-content h6 {
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: bold;
            color: #2c3e50;
          }
          .temp-pdf-content h1 { font-size: 24px; }
          .temp-pdf-content h2 { font-size: 20px; }
          .temp-pdf-content h3 { font-size: 18px; }
          .temp-pdf-content p { margin-bottom: 16px; }
          .temp-pdf-content ul, .temp-pdf-content ol { margin-bottom: 16px; padding-left: 20px; }
          .temp-pdf-content li { margin-bottom: 8px; }
          .temp-pdf-content blockquote {
            border-left: 4px solid #dfe2e5;
            padding-left: 16px;
            margin: 16px 0;
            color: #6a737d;
            font-style: italic;
          }
          .temp-pdf-content code {
            background-color: #f6f8fa;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
            font-size: 85%;
          }
          .temp-pdf-content pre {
            background-color: #f6f8fa;
            padding: 16px;
            border-radius: 6px;
            overflow: auto;
            font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
            font-size: 85%;
            line-height: 1.45;
          }
          .temp-pdf-content table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 16px;
          }
          .temp-pdf-content th, .temp-pdf-content td {
            border: 1px solid #dfe2e5;
            padding: 8px 12px;
            text-align: left;
          }
          .temp-pdf-content th {
            background-color: #f6f8fa;
            font-weight: bold;
          }
        </style>
        <div class="temp-pdf-content">${htmlContent}</div>
      `;

      // 添加到DOM中进行渲染
      document.body.appendChild(tempContainer);

      // 等待渲染完成
      await new Promise(resolve => setTimeout(resolve, 500));

      console.log('开始渲染HTML到Canvas...');
      const canvas = await html2canvas(tempContainer, {
        scale: 2, // 提高分辨率以减少模糊
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
        logging: false,
        scrollX: 0,
        scrollY: 0,
        foreignObjectRendering: false, // 禁用以提高兼容性
        removeContainer: false
      });

      // 移除临时容器
      document.body.removeChild(tempContainer);

      console.log('Canvas渲染完成, 尺寸:', canvas.width, 'x', canvas.height);

      const imgData = canvas.toDataURL('image/png', 1.0); // 使用PNG无损格式获得最佳质量
      console.log('图片数据转换完成');

      // 创建PDF文档
      const pdf = new jsPDF('p', 'mm', 'a4');
      const pageWidth = 210; // A4宽度
      const pageHeight = 297; // A4高度
      const margin = 10; // 页边距
      const contentWidth = pageWidth - 2 * margin;
      const contentHeight = pageHeight - 2 * margin;

      // 计算图片在PDF中的尺寸
      const imgWidth = contentWidth;
      const imgHeight = (canvas.height * contentWidth) / canvas.width;

      console.log('PDF页面设置:', {
        pageWidth,
        pageHeight,
        imgWidth,
        imgHeight: imgHeight,
        totalPages: Math.ceil(imgHeight / contentHeight)
      });

      let yPosition = margin;
      let remainingHeight = imgHeight;
      let sourceY = 0;
      let pageCount = 1;

      console.log('开始生成PDF页面...');

      while (remainingHeight > 0) {
        // 当前页可用的内容高度
        const currentPageHeight = Math.min(remainingHeight, contentHeight);

        // 计算源图片的裁剪区域
        const sourceHeight = (currentPageHeight * canvas.width) / contentWidth;

        // 创建临时canvas来裁剪图片
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        tempCanvas.width = canvas.width;
        tempCanvas.height = sourceHeight;

        if (tempCtx) {
          tempCtx.drawImage(
            canvas,
            0, sourceY, // 源图片的起始位置
            canvas.width, sourceHeight, // 源图片的尺寸
            0, 0, // 目标位置
            canvas.width, sourceHeight // 目标尺寸
          );

          const pageImgData = tempCanvas.toDataURL('image/png', 1.0);

          // 添加图片到PDF
          pdf.addImage(pageImgData, 'PNG', margin, yPosition, imgWidth, currentPageHeight);

          console.log(`第${pageCount}页添加完成`);
        }

        // 更新位置和剩余高度
        remainingHeight -= currentPageHeight;
        sourceY += sourceHeight;

        // 如果还有内容，添加新页面
        if (remainingHeight > 0) {
          pdf.addPage();
          yPosition = margin;
          pageCount++;
        }
      }

      console.log(`PDF生成完成，共${pageCount}页，开始下载...`);

      // 保存PDF文件
      pdf.save(filename);

      console.log('PDF导出流程完成');

      // 在桌面环境中显示成功消息
      if (isDesktop) {
        alert(`PDF导出成功！

文件已保存到下载目录。
共生成 ${pageCount} 页

此PDF支持完美的中文显示。`);
      }

    } catch (error) {
      console.error('PDF导出失败:', error);

      // 提供更详细的错误信息
      let errorMessage = 'PDF导出失败';
      if (error instanceof Error) {
        errorMessage += ': ' + error.message;
      }

      // 根据错误类型提供不同的建议
      let suggestions = '';
      if (error instanceof Error) {
        if (error.message.includes('导入') || error.message.includes('import')) {
          suggestions = '\n\n可能的解决方案：\n1. 检查网络连接\n2. 重新启动应用\n3. 尝试使用其他导出格式（HTML）';
        } else if (error.message.includes('Canvas') || error.message.includes('html2canvas')) {
          suggestions = '\n\n可能的解决方案：\n1. 确保内容已完全加载\n2. 尝试切换到"仅预览"模式\n3. 等待几秒后再尝试导出';
        } else {
          suggestions = '\n\n可能的解决方案：\n1. 确保内容已加载完成\n2. 尝试切换到预览模式后再导出\n3. 检查浏览器控制台获取更多信息';
        }
      }

      alert(errorMessage + suggestions);
    }
  },

  // 打开打印预览（获得可选择文字的PDF）
  openPrintPreview: (content: string, filename: string = '未命名.md') => {
    try {
      console.log('打开打印预览...');

      // 转换Markdown为HTML
      const htmlContent = marked(content);

      // 创建打印样式的HTML
      const printHTML = `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>${filename.replace(/\.md$/, '')} - 打印预览</title>
  <style>
    @media print {
      @page {
        size: A4;
        margin: 2cm;
      }
      body {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
      }
    }

    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "SimSun", sans-serif;
      font-size: 14px;
      line-height: 1.6;
      color: #333333;
      max-width: 210mm;
      margin: 0 auto;
      padding: 20px;
      background: white;
    }

    h1, h2, h3, h4, h5, h6 {
      margin-top: 24px;
      margin-bottom: 16px;
      font-weight: bold;
      color: #2c3e50;
      page-break-after: avoid;
    }

    h1 { font-size: 28px; border-bottom: 2px solid #eee; padding-bottom: 8px; }
    h2 { font-size: 22px; }
    h3 { font-size: 18px; }
    h4 { font-size: 16px; }
    h5 { font-size: 14px; }
    h6 { font-size: 12px; }

    p {
      margin-bottom: 16px;
      text-align: justify;
    }

    ul, ol {
      margin-bottom: 16px;
      padding-left: 20px;
    }

    li {
      margin-bottom: 8px;
    }

    blockquote {
      border-left: 4px solid #dfe2e5;
      padding-left: 16px;
      margin: 16px 0;
      color: #6a737d;
      font-style: italic;
      background: #f9f9f9;
      padding: 10px 16px;
    }

    code {
      background-color: #f6f8fa;
      padding: 2px 6px;
      border-radius: 3px;
      font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, "Courier New", monospace;
      font-size: 85%;
      color: #d73a49;
    }

    pre {
      background-color: #f6f8fa;
      padding: 16px;
      border-radius: 6px;
      overflow: auto;
      font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, "Courier New", monospace;
      font-size: 85%;
      line-height: 1.45;
      border: 1px solid #e1e4e8;
      page-break-inside: avoid;
    }

    pre code {
      background: none;
      padding: 0;
      color: inherit;
    }

    table {
      border-collapse: collapse;
      width: 100%;
      margin-bottom: 16px;
      page-break-inside: avoid;
    }

    th, td {
      border: 1px solid #dfe2e5;
      padding: 8px 12px;
      text-align: left;
    }

    th {
      background-color: #f6f8fa;
      font-weight: bold;
    }

    img {
      max-width: 100%;
      height: auto;
      page-break-inside: avoid;
    }

    hr {
      border: none;
      border-top: 2px solid #eee;
      margin: 24px 0;
    }

    @media screen {
      .no-print {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1000;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .print-btn {
        background: #007bff;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
        margin-left: 10px;
        transition: background 0.2s;
      }

      .print-btn:hover {
        background: #0056b3;
      }
    }

    @media print {
      .no-print {
        display: none;
      }
    }
  </style>
</head>
<body>
  <div class="no-print">
    <button class="print-btn" onclick="window.print()">📄 导出PDF</button>
    <button class="print-btn" onclick="window.print()">🖶️ 打印</button>
    <button class="print-btn" onclick="window.close()">❌ 关闭</button>
  </div>

  ${htmlContent}

</body>
</html>`;

      // 在新窗口中打开
      const printWindow = window.open('', '_blank');
      if (printWindow) {
        printWindow.document.write(printHTML);
        printWindow.document.close();

        // 聚焦新窗口
        printWindow.focus();
      } else {
        alert('无法打开打印预览窗口，请检查浏览器的弹窗设置。');
      }

    } catch (error) {
      console.error('打开打印预览失败:', error);
      alert('打开打印预览失败，请重试。');
    }
  },

  // 导出为Word文档（使用HTML格式，Word兼容）
  exportToWord: async (content: string, filename: string) => {
    try {
      console.log('开始Word导出:', filename);

      // 转换Markdown为HTML
      const htmlContent = marked(content);

      // 创建完整的HTML文档，包含Word兼容的样式
      const wordHTML = `<!DOCTYPE html>
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word">
<head>
  <meta charset="UTF-8">
  <meta name="ProgId" content="Word.Document">
  <title>导出的文档</title>
  <style>
    body {
      font-family: "Times New Roman", "宋体", serif;
      font-size: 12pt;
      line-height: 1.5;
      color: #000000;
      margin: 0;
      padding: 20pt;
    }
    h1, h2, h3, h4, h5, h6 {
      color: #2c3e50;
      margin-top: 12pt;
      margin-bottom: 6pt;
      font-weight: bold;
    }
    h1 { font-size: 18pt; }
    h2 { font-size: 16pt; }
    h3 { font-size: 14pt; }
    p { margin: 6pt 0; }
    code {
      font-family: "Courier New", monospace;
      background-color: #f4f4f4;
      padding: 2px 4px;
    }
    table {
      border-collapse: collapse;
      width: 100%;
      margin: 12pt 0;
    }
    th, td {
      border: 1px solid #000000;
      padding: 6pt 8pt;
    }
    th { background-color: #f2f2f2; }
  </style>
</head>
<body>
  ${htmlContent}
</body>
</html>`;

      const blob = new Blob([wordHTML], { type: 'application/msword' });
      saveAs(blob, filename.endsWith('.doc') ? filename : `${filename}.doc`);

      console.log('Word导出成功');
    } catch (error) {
      console.error('Word导出失败:', error);
      throw new Error(`Word导出失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }
};

export const storageUtils = {
  // 保存到本地存储
  save: (key: string, value: any) => {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error('Failed to save to localStorage:', error);
    }
  },

  // 从本地存储读取
  load: <T>(key: string, defaultValue: T): T => {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : defaultValue;
    } catch (error) {
      console.error('Failed to load from localStorage:', error);
      return defaultValue;
    }
  },

  // 从本地存储删除
  remove: (key: string) => {
    try {
      localStorage.removeItem(key);
    } catch (error) {
      console.error('Failed to remove from localStorage:', error);
    }
  }
};
